<template>
    <div>
        <el-form
                :model="form"
                ref="form"
                label-width="120px"
                label-position="right"
                class="demo-ruleForm"
                style="display: inline-block;width: 100%"
        >
            <el-form-item label="时间/步长">
                <el-date-picker
                        v-model="orderTime"
                        type="datetimerange"
                        align="right"
                        style="width: 40%"
                        :picker-options="pickerOptions"
                        :start-placeholder="passtime|dateFormat('yyyy-MM-dd HH:mm:ss')"
                        :end-placeholder="nowtime |dateFormat('yyyy-MM-dd HH:mm:ss')"
                        value-format="timestamp"
                        :default-time="['00:00:00', '23:59:59']"
                        @change="getMinStep()">
                </el-date-picker>
                <el-select v-model="form.step"
                           filterable
                           allow-create
                           default-first-option
                           style="margin-left: 10px;width: 130px"
                           placeholder="请选择步长"
                           @change="getOption()"
                >
                    <el-option
                            v-for="(item, index) in allStep"
                            :value="item.value"
                            :label="item.label"
                            :key="index"
                    ></el-option>
                </el-select>
                <span style="display: inline-block;color: #ababab">
                    (单位s,建议最小步长{{this.minStep}})
                    </span>
                <span style="display:inline-block ;float: right">
                    <el-button
                            size="mini"
                            title="自定义"
                            icon="el-icon-tickets"
                            circle
                            @click="doQuery()"
                    >{{queryTitle}}</el-button>
                </span>
                <span style="display:inline-block;float: right">
                    <el-button
                            size="mini"
                            title="查询"
                            icon="el-icon-search"
                            type="primary"
                            circle
                            style="margin-left: 10px;margin-right: 10px"
                            @click="getOption()"
                    >查询</el-button>
                </span>
            </el-form-item>
            <el-form-item label="自定义" v-if="to_query" style="width: 60%;display: inline-block">
                <el-input @change="getOption()" v-model="form.query"></el-input>
            </el-form-item>
            <!--<el-form-item label="开始时间" style="width: 45%;display: inline-block">-->
            <!--<el-date-picker type="date" placeholder="选择开始时间" v-model="startTime" value-format="timestamp"-->
            <!--&gt;</el-date-picker>-->
            <!--</el-form-item>-->
            <!--<el-form-item label="结束时间" style="width: 45%;display: inline-block">-->
            <!--<el-date-picker type="date" placeholder="选择结束时间" v-model="endTime" value-format="timestamp"-->
            <!--&gt;</el-date-picker>-->
            <!--</el-form-item>-->
            <!--<el-form-item label="步长" style="width: 45%;display: inline-block">-->
            <!--<span style="display: inline-block;color: #ababab">-->
            <!--(单位s,建议最小步长{{this.minStep}})-->
            <!--</span>-->
            <!--</el-form-item>-->
            <el-form-item label="字段" v-if="!to_query" style="width: 30%;display: inline-block">
                <el-select v-model="queryText"
                           filterable
                           class="selectbox"
                           @change="getOption()"
                           placeholder="请类型">
                    <el-option
                            v-for="(item, index) in queryType"
                            :value="item.value"
                            :label="item.label"
                            :key="index"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="函数A" v-if="!to_query" style="width: 30%;display: inline-block">
                <el-select v-model="queryFunA"
                           filterable
                           class="selectbox"
                           @change="getOption()"
                           placeholder="请类型">
                    <el-option
                            v-for="(item, index) in queryFunAType"
                            :value="item.value"
                            :label="item.label"
                            :key="index"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="函数B" v-if="!to_query" style="width: 30%;display: inline-block">
                <el-select v-model="queryFunB"
                           filterable
                           class="selectbox"
                           @change="getOption()"
                           placeholder="请类型">
                    <el-option
                            v-for="(item, index) in queryFunBType"
                            :value="item.value"
                            :label="item.label"
                            :key="index"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="端口" v-if="!to_query" style="width: 30%;display: inline-block">
                <el-input @change="getOption()" v-model="if_index" placeholder="多个端口时用'|'分隔 例:80|81" class="selectbox"></el-input>
            </el-form-item>
            <el-form-item label="间隔" v-if="!to_query" style="width: 30%;display: inline-block">
                <el-select v-model="interval"
                           filterable
                           allow-create
                           class="selectbox"
                           default-first-option
                           @change="getOption()"
                           placeholder="请选择间隔">
                    <el-option
                            v-for="(item, index) in allInterval"
                            :value="item.value"
                            :label="item.label"
                            :key="index"
                    ></el-option>
                </el-select>
                <!--<span style="display: inline-block;color: #ababab">-->
                <!--(建议最小间隔为{{this.minInterval}}的两倍)-->
                <!--</span>-->
            </el-form-item>
            <el-form-item label="单位" v-if="!to_query" style="width: 30%;display: inline-block">
                <el-select v-model="unitText"
                           class="selectbox"
                           @change="getOption()"
                           placeholder="请类型">
                    <el-option
                            v-for="(item, index) in unitType"
                            :value="item.value"
                            :label="item.label"
                            :key="index"
                    ></el-option>
                </el-select>
            </el-form-item>
            <!--<el-form-item label="日期" style="display: inline-block">-->
            <!--<el-date-picker-->
            <!--v-model="orderTime"-->
            <!--type="datetimerange"-->
            <!--align="right"-->
            <!--:picker-options="pickerOptions"-->
            <!--:start-placeholder="passtime|dateFormat('yyyy-MM-dd HH:mm:ss')"-->
            <!--:end-placeholder="nowtime |dateFormat('yyyy-MM-dd HH:mm:ss')"-->
            <!--value-format="timestamp"-->
            <!--:default-time="['00:00:00', '23:59:59']"-->
            <!--@change="getMinStep()">-->
            <!--</el-date-picker>-->
            <!--</el-form-item>-->
        </el-form>
        <!--<v-loading v-if="loadingStatus"></v-loading>-->
        <v-echartsc ref="echarts" id="echarts-img" :loadingStatus="loadingStatus"
                    :option="viewChart.option">
        </v-echartsc>
        <span style="display: inline-block;color: #ababab;margin-left: 85px;margin-bottom: 5px">
            Query: {{form.query}}
        </span>
    </div>
</template>

<script>
  export default {
    props: ['host', 'job'],
    name: "index",
    data () {
      return {
        viewChart: { option: {} },
        data: {},
        to_query: false,
        queryFunA: 'sum',
        queryFunB: 'rate',
        queryText: 'ifHCOutOctets',
        unitText: '8/1000/1000/1000',
        interval: '5m',
        if_index: '',
        is_query: 0,
        orderTime: [],
        jobType: '',
        queryTitle: '自定义',
        // metricData:[],
        nowtime: '',
        // mouseCurValue:[],
        passtime: '',
        minStep: 18,
        minInterval: '',
        loadingStatus: false,
        pickerOptions: {
          shortcuts: [{
            text: '最近五分钟',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 60 * 1000 * 5);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近十分钟',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 60 * 1000 * 10);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近十五分钟',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 60 * 1000 * 15);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近半小时',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 60 * 1000 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一小时',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三小时',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 3);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近六小时',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 6);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近十二小时',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 12);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一天',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', [start, end]);
            }
          },
            {
              text: '最近三天',
              onClick (picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
                picker.$emit('pick', [start, end]);
              }
            },
          ]
        },
        form: {
          host: '',
          start: '',
          end: '',
          step: 300,
          query: '',
        },
        // allStep:[],
        allStep: [{ value: '60', label: '60' }, { value: '100', label: '100' }, { value: '200', label: '200' }],
        unitType: [
          { value: '', label: '不选择' },
          { value: '8/1000/1000/1000', label: '8/1000/1000/1000(G)' },
          { value: '8/1024/1024/1024', label: '8/1024/1024/1024(G)' },
        ],
        queryFunAType: [
          { value: '', label: '不选择' },
          { value: 'sum', label: 'sum' },
          { value: 'avg', label: 'avg' },
          { value: 'count', label: 'count' },
          { value: 'max', label: 'max' },
          { value: 'min', label: 'min' },
          { value: 'sort', label: 'sort' },
          { value: 'sqrt', label: 'sqrt' },
          { value: 'floor', label: 'floor' },
          { value: 'ceil', label: 'ceil' },
        ],
        queryFunBType: [
          { value: '', label: '不选择' },
          { value: 'rate', label: 'rate' },
          { value: 'irate', label: 'irate' },
        ],
        queryType: [],
        allInterval: [],
        // allQueryType: [{ value: 'in', label: 'In' }, { value: 'out', label: 'Out' }, {
        //   value: 'in_sum',
        //   label: 'In(sum)'
        // }, { value: 'out_sum', label: 'Out(sum)' }],
      }
    },
    computed: {},
    mounted () {
      // this.text()
      // this.form.host = this.host
      // this.getOption()
    },
    watch: {
      host (val, oldVal) {//监听host变化
        this.form.host = val
        this.queryFunA = 'sum'
        this.queryFunB = 'rate'
        this.queryText = 'ifHCOutOctets'
        this.unitText = '8/1000/1000/1000',
            this.if_index = '',
            this.is_query = 0,
            this.interval = '5m',
            this.form.start = '',
            this.form.end = '',
            this.form.step = 300,
            this.form.query = '',
            this.orderTime = [],
            this.nowtime = Date.parse(new Date()) / 1000;
        this.passtime = Date.parse(new Date()) / 1000 - 3600;
        this.makeQuery()
        this.getQueryType(val)
      },
      job (val, oldVal) {
        this.getMinInterval(val)
      },
    },
    methods: {
      getOption () {
        // let data =[['time','tardata']]
        this.viewChart.option = {}
        this.form.step = Number(this.form.step)
        // console.log(this.form.start)
        // console.log(this.orderTime)
        if (this.orderTime.length > 0) {
          this.form.start = Math.floor(Number(this.orderTime[0] / 1000))
          this.form.end = Math.floor(Number(this.orderTime[1] / 1000))
        } else {
          this.form.start = ''
          this.form.end = ''
        }
        this.loadingStatus = true
        this.makeQuery()
        this.$api.get("prometheus.get_target_image", this.form).then(res => {
          if (res.status === 1) {
            this.data = res.data
            // this.metricData = []
            // 几条折线数据
            // console.log(this.data)
            var lineData = [];
            var metricData = [];
            for (let i = 0; i < this.data.result.length; i++) {
              let dataA = []
              this.data.result[i].values.forEach((e) => {
                let k = []
                k = [e[0] * 1000, Math.floor(e[1] * 100) / 100]
                dataA.push(k)
              })
              let s_temp = {
                name: this.data.result[i].metric.ifIndex,
                type: "line",
                symbol: 'none',
                data: dataA
              }
              lineData.push(s_temp)
              metricData.push(this.data.result[i].metric)
            }
            this.viewChart.option = {
              title: {},
              tooltip: {
                trigger: 'axis',
                show: true,
                textStyle: {
                  align: 'left'
                },
                // formatter: '{a0}:{c0}G',
                formatter: function (params) {
                  var relVal = params[0].axisValueLabel
                  for (var i = 0, l = params.length; i < l; i++) {
                    relVal += '<br/>' + params[i].marker + params[i].seriesName + ' : ' + params[i].value[1] + 'G'
                  }
                  return relVal
                },
                enterable: true,
                extraCssText: "max-width:60%;max-height:83%;overflow:auto",
              },
              xAxis: {
                type: 'time',
                splitLine: { show: false },
              },
              yAxis: {
                type: 'value',
                axisLine: { show: false },
                axisTick: { show: false },
                // scale: true, //自适应
                min: function(value) {//取最小值向下取整为最小刻度
                  return Math.floor(value.min)
                },
                max: function(value) {//取最大值向上取整为最大刻度
                  return  Math.ceil(value.max)
                },
                // minInterval: 0.1, //分割刻度
                axisLabel: {
                  formatter: this.unitText != '' ? '{value} G' : '{value}',
                }
              },
              series: lineData
            }
          }
          this.loadingStatus = false
          // this.$forceUpdate()
        }).catch(() => {
        });
      },
      doQuery () {
        this.to_query = !this.to_query
        this.is_query === 0 ? this.is_query = 1 : this.is_query = 0
        this.form.start = ''
        this.form.end = ''
        this.form.query = ''
        if (this.to_query === true) {
          this.queryTitle = '默认'
        } else {
          this.queryTitle = '自定义'
        }
      },
      getMinStep () {
        this.minStep = Math.round(((this.orderTime[1] - this.orderTime[0]) / 1000) / 200)
        this.getOption()
      },
      // 获取图方法
      getQueryType (item) {
        this.$api.get("prometheus.get_target_image_func", { host: item }).then(res => {
          if (res.status === 1) {
            this.queryType = []
            let t = res.data
            t.forEach((e) => {
              let d = { 'value': e, 'label': e }
              this.queryType.push(d)
            })
          }
        }).catch(() => {
        });
      },
      // 获取最小间隔
      getMinInterval (item) {
        this.$api.get("prometheus.job_detail", { job_name: item }).then(res => {
          if (res.status === 1) {
            this.minInterval = res.data.scrape_interval
            this.jobType = res.data.job_type
            let a = this.minInterval.substring(0, this.minInterval.indexOf("m"));
            let b = [{ value: a * 2 + 'm', label: a * 2 + 'm' }, {
              value: a * 3 + 'm',
              label: a * 3 + 'm'
            }, { value: a * 4 + 'm', label: a * 4 + 'm' }]
            this.allInterval = b
          }
        }).catch(() => {
        });
      },
      // 拼接query
      makeQuery () {
        let kA = this.queryFunA
        let kB = this.queryFunB
        let ktext = this.queryText
        let q = ''
        if (ktext) {
          if (this.jobType = 'snmp_exporter') {

            if (this.if_index != "") {
              q = ktext + '{instance="' + this.form.host + '",ifIndex=~"' + this.if_index + '"}'
            } else {
              q = ktext + '{instance="' + this.form.host + '"}'
            }
          } else {
            q = ktext + '{instance="' + this.form.host + '"}'
          }
        }

        if (kB === 'rate' || kB === 'irate') {
          q = kB + '(' + q + '[' + this.interval + '])'
        } else {
          q = kB + '(' + q + ')'
        }
        // console.log(kB)
        if (kA) {
          q = kA + '(' + q + ')'
        }
        if (this.jobType = 'snmp_exporter') {
          if (this.unitText != "") {
            q = q + '*' + this.unitText
          }
        }
        // q = q + '*' + this.unitText
        // console.log(q)
        this.form.query = q
      }
    }
  }
</script>

<style scoped>
    .selectbox {
        width: 100%;
        max-width: 260px;
        min-width: 150px;
    }

</style>